﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
using System.Diagnostics;
using SQLServerSyncServer;

namespace SQLServerSyncClient
{
    class UDP
    {
        UdpClient recv;
        IPEndPoint IpEndPoint;

        public UDP(int Port)
        {
            IpEndPoint = new IPEndPoint(IPAddress.Any, Port);
            recv = new UdpClient(IpEndPoint);
        }
        public void Send(ref ListView lv, string ip, int GroupPort, string message)
        {
            IPAddress GroupAddress = IPAddress.Parse(ip);

            UdpClient sender = new UdpClient();

            IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort);

            try
            {
                byte[] bytes = Encoding.ASCII.GetBytes(message);

                sender.Send(bytes, bytes.Length, groupEP);
                Log.Message(ref lv, DateTime.Now, "发送:" + message);
                sender.Close();

            }
            catch (Exception e)
            {
                Log.Message(ref lv, DateTime.Now, e.Message);
            }
        }


        //public string Receive()
        //{
        //    string sqlrecv = "";

        //    byte[] bytes = recv.Receive(ref IpEndPoint);
        //    sqlrecv = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
        //    if(sqlrecv.Length > 0)
        //    {
        //        Debug.WriteLine("从" + IpEndPoint.ToString() + " 收到 " + sqlrecv);
        //        lock (Form1.sqlArray.SyncRoot)
        //        {
        //            //ReceiveCache.receiveQueue.Enqueue(sqlrecv);
        //            Form1.sqlArray.Add(sqlrecv);
        //        }
        //    }

        //    return sqlrecv;
        //}

        public object ReceiveObject()
        {

            byte[] bytes = recv.Receive(ref IpEndPoint);
            object recvObj = ObjectTransfer.BytesToObject(bytes);

            return recvObj;
        }

        public void Close()
        {
            recv.Close();
        }
    }
}
